<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/23
 * Time: 16:32
 */

namespace app\api\controller\android\v4;


use foxyZeng\huyi\HuYiSMS;
use think\Cache;
use think\Controller;
use think\Exception;
use think\Request;
use app\api\model\Authority;

class Login extends Controller
{
    /**
     * @param array $data
     * @return array
     * $data=['id','name'=>'123']  id必填，name选填，默认值为123（有默认值时key不能为int）
     */
    public function post(array $data)
    {
        if (empty($data)) {
            r_date([], 300, '提交数据不正确');
        }
        $return = [];

        foreach ($data as $key => $item) {//key course_id item 1

            if (!is_int($key)) {
                $val = Request::instance()->post($key);

                if ($val!='') {
                    $return[$key] = trim($val);
                } else {
                    $return[$key] = trim($item);
                }
            } else {
                $val = Request::instance()->post($item);
                if (!isset($val)) {
                    r_date([], 300, "缺少 $item 数据");
                }
                $return[$item] = trim($val);
            }
        }
        return $return;
    }
    /**
     * 用户注册
     */
    public function register(){
        $data=$this->post(['mobile','username','code','password','sex','age']);
        $data['avatar']="https://www.yiniaoweb.com/static/images/login/tx.png";
        if (!is_mobile($data['mobile'])) {
            r_date([], 300, '电话号码不符合规则');
        }
        if (!is_password($data['password'])) {
            r_date([], 300, '请输入6~12位数字或字母为密码');
        }
        $s_verify = Cache::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');

        }
        Cache::clear(md5($data['mobile']));
        $user = db("user")->where(['mobile'=>$data['mobile']])->find();
        if ($user) {
            if($user['status']!=3){
                r_date([], 300, '该手机号已经注册');
            }
        }
        $data['password']=encrypt($data['password']);
        $data['created_time']=time();
        $data['status']=1;
        unset($data['code']);
        \db()->startTrans();
        try {
            $user_id=\db("user")->insertGetId($data);
            \db()->commit();
            r_date(['user_id'=>$user_id], 200, '注册成功');
        } catch (Exception $e) {
            \db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    /**
     * 完工
     */
    public function finished()
    {
        $data = Request::instance()->post('order_id');
        $res  = db('order')->where(['order_id' => $data['order_id']])->update(['state' => 6, 'update_time' => time()]);
        if ($res) {
            res_date([], 200, '新增成功');
        } else {
            res_date([], 300, '操作失败');
        }
    }
    /**
     * 重置密码
     */
    public function reset_password(){
        $data= $this->post(['mobile','code','password']);
        if(!is_password($data['password'])){
            r_date([], 300, '请输入6~12位数字或字母为密码');
        }
        $s_verify = Cache::get(md5($data['mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date(null, 300, '验证码错误');
        }
        Cache::clear(md5($data['mobile']));
        $user=db('user')
            ->where(['mobile'=>$data['mobile']])
            ->find();
        if(!$user){
            r_date(null, 300, '该手机号未注册');
        }
        $res=db('user')->where(['mobile'=>$data['mobile']])->update(['password'=>encrypt($data['password'])]);
        if($res!==false){
            r_date();
        }
        r_date(null,300,'修改失败，请刷新后重试');
    }

    /**
     * 登录
     */
    public function login(){
        $data=$this->post(['mobile','password','registrationId']);
        $is_mobile=db('user')
            ->where(['mobile'=>$data['mobile']])
            ->find();
        if(!$is_mobile){
            r_date(null, 300, '该手机号未注册，无法登录');
        }
        $user=db('user')
            ->where([
                'mobile'=>$data['mobile'],
                'password'=>encrypt($data['password']),
            ])
            ->find();
        if(!$user){
            r_date(null, 300, '账号或密码错误');
        }
        if($user['status']==1){
            r_date(null, 300, '请等待审核');
        }
        if($user['status']==2){
            r_date(null, 300, '该用户已冻结');
        }
        $res=db('user')
            ->where(['user_id'=>$user['user_id']])
            ->update([
                'last_login_time'=>time(),
                'registrationId'=>$data['registrationId'],
                'access_token' => md5(uniqid('check', true))
            ]);
        if($res!==false){
            $retrun=db('user')->field('user.user_id,user.mobile,user.username,user.avatar,user.sex,user.access_token,st.store_name,user.reserve')->join('store st','user.store_id=st.store_id','left')->where(['user.user_id'=>$user['user_id']])->find();

            r_date($retrun);
        }
        r_date(null,300,'请刷新后登录');
    }
    /**
     * 发送验证码
     */
    public function send_code(){
        $data=$this->post(['mobile']);
        $user = db("user")->where(['mobile'=>$data['mobile']])->find();
        if ($user) {
            if($user['status']!=3){
                r_date([], 300, '该手机号已经注册');
            }
        }
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms=new HuYiSMS();
        $code=trim(mt_rand(100000,999999));
        Cache::set(md5($data['mobile']),$code,300);
        $content = "您的验证码是：{$code}。请不要把验证码泄露给其他人。";
        try{
            $sms->send($data['mobile'],$content);
            r_date('[]',200,'发送成功');
        }catch (Exception $e){
            r_date([],300,$e->getMessage());
        }
    }
    /**
     * 发送验证码
     */
    public function send_code1(){
        $data=$this->post(['mobile']);
        $user = db("user")->where(['mobile'=>$data['mobile']])->find();
        if(!$user){
            r_date([], 300, '该手机号未注册，无法登录');
        }
        vendor('foxyzeng.huyi.HuYiSMS');
        $sms=new HuYiSMS();
        $code=trim(mt_rand(100000,999999));
        Cache::set(md5($data['mobile']),$code,300);
        $content = "您的验证码是：{$code}。请不要把验证码泄露给其他人。";
        try{
            $sms->send($data['mobile'],$content);
            r_date([],200,'发送成功');
        }catch (Exception $e){
            r_date([],300,$e->getMessage());
        }
    }




    /***
     *
     * 退出
     *
     */
    public function logout(){
        $model=new Authority();
        $user=$model->check(1);
        $res=db('user')
            ->where(['user_id'=>$user['user_id']])
            ->update([
                'access_token' =>'',
                'lat' =>'',
                'lng' =>'',
            ]);
        if($res){
            r_date(null,200,'退出成功');
        }else{
            r_date(null,300,'退出失败');
        }
    }


}